import Dialog from "@vant/weapp/dialog/dialog";
Page({
  data: {
    showAdd: false, //显示新增页面
    showEdit: false, //弹出编辑页面
    onBeforeClose: function (action) {
      if (action === "cancel") {
        return true;
      }
    },
    AddressList: [
      {
        name: "牛爷爷",
        value: "翻斗花园A0022",
        number: "111111",
      },
      {
        name: "胡图图",
        value: "翻斗花园A001",
        number: "222222",
      },
    ],
    radio: 0, //选中的radio的索引值
    form: {
      name: "",
      number: "",
      address: "",
    },
  },
  onShow() {
    if (typeof this.getTabBar === "function" && this.getTabBar()) {
      const route = "/" + this.route;
      const tabList = this.getTabBar().data.list;
      const current = tabList.find((i) => i.pagePath === route);
      if (current) {
        this.getTabBar().setData({ value: current.value });
      }
    }
  },
  radioChange(event) {
    this.setData({
      radio: event.detail,
    });
    console.log(this.data.radio);
  },
  // 左右滑动删除
  onSwipeClose(event) {
    const { position, instance } = event.detail;
    switch (position) {
      case "left":
        break;
      case "cell":
        instance.close();
        break;
      case "right":
        console.log("确定删除吗?");
        Dialog.confirm({
          title: "提示",
          message: "确定删除吗？",
        })
          .then(() => {
            //确定
            console.log("确定");
            instance.close();
          })
          .catch(() => {
            //取消
            console.log("取消");
            instance.close();
          });
        break;
    }
  },
  //编辑地址信息
  edit(e) {
    const index = e.currentTarget.dataset.index;
    const item = this.data.AddressList[index];
    this.setData({
      showEdit: true,
      // radio: index,
      form: {
        name: item.name,
        number: item.number,
        address: item.value, // 注意这里是 value 字段
      },
    });
  },

  onDialogConfirm() {
    const phone = this.data.form.number;
    const phoneReg = /^1[3-9]\d{9}$/;
    if (!phoneReg.test(phone)) {
      wx.showToast({
        title: "手机号格式不正确",
        icon: "none",
      });
      return;
    }
    console.log("输入校验通过");
    // 校验通过，关闭弹窗
    this.setData({
      showAdd: false,
      showEdit: false,
    });
  },
  //关闭弹窗
  onDialogClose() {
    this.setData({
      form: {
        name: "",
        number: "",
        address: "",
      },
    });
  },
  //弹出新增地址
  addAddress() {
    this.setData({
      showAdd: true,
    });
  },
  //监听输入
  onNameInput(e) {
    this.setData({
      "form.name": e.detail,
    });
  },
  onNumberInput(e) {
    this.setData({
      "form.number": e.detail,
    });
  },
  onAddressInput(e) {
    this.setData({
      "form.address": e.detail,
    });
  },
});
